<template>
  <u-popup
    :show="show"
    :round="10"
    @close="handleClose"
    :closeable="true"
    bgColor="#fff"
    zIndex="10082"
    :closeOnClickOverlay="false"
  >
    <view class="flex flex-col h-[50vh] popup-common" @touchmove.prevent.stop>
      <view class="head">
        <view class="title">支付密码</view>
      </view>

      <view class="flex-1 px-[36rpx] py-[30rpx]">
        <!-- 密码输入框 -->
        <view class="password-input-container">
          <u-code-input v-model="password" size="80rpx" focus space="20rpx" :maxlength="6" dot @finish="confirmPassword" />
        </view>
        <view class="error-tip" v-if="errorMessage">{{ errorMessage }}</view>
      </view>

      <view class="btn-wrap">
        <button
          class="primary-btn-bg btn"
          hover-class="none"
          :loading="loading"
          :disabled="password.length !== 6"
          @click="confirmPassword"
        >
          确认
        </button>
      </view>
    </view>
  </u-popup>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { checkPayPassword } from "@/app/api/auth";

const show = ref(false);
const loading = ref(false);
const password = ref("");
const errorMessage = ref("");

const emits = defineEmits(["close", "success"]);

/**
 * 打开支付密码弹窗
 */
const open = () => {
  password.value = "";
  errorMessage.value = "";
  show.value = true;
};

/**
 * 确认支付密码
 */
const confirmPassword = async () => {
  if (password.value.length !== 6) {
    errorMessage.value = "请输入6位支付密码";
    return;
  }
  if (loading.value) return;
  loading.value = true;
  errorMessage.value = "";
  try {
    const res: any = await checkPayPassword({
      pay_password: password.value,
    });

    if (res.code === 1) {
      emits("success");
      handleClose();
    } else {
      errorMessage.value = res.msg || "支付密码错误";
      password.value = "";
    }
  } catch (error: any) {
    errorMessage.value = error.msg || "支付密码错误";
    password.value = "";
  } finally {
    loading.value = false;
    uni.hideKeyboard();
  }
};

/**
 * 关闭弹窗
 */
const handleClose = () => {
  show.value = false;
  loading.value = false;
  password.value = "";
  errorMessage.value = "";
  emits("close");
};

defineExpose({
  open,
});
</script>

<style lang="scss" scoped>
.password-input-container {
  margin-bottom: 30rpx;
  display: flex;
  justify-content: center;
}

.error-tip {
  color: #ff4757;
  font-size: 24rpx;
  text-align: center;
  margin-top: 20rpx;
}
</style>
